﻿using System;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media;

namespace WPFTemplateLib.WpfConverters
{
    /// <summary>
    /// 所有支持的数据类型转图片资源转换器（支持 string、Stream(MemoryStream)、Uri、byte[] 等）
    /// </summary>
    public class AllTypeToImageSourceConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                if (value == null)
                {
                    return null;
                }

                var converter = new ImageSourceConverter();
                Type sourceType = value.GetType();
                if (!converter.CanConvertFrom(sourceType))
                {
                    //经测试 MemoryStream 是支持的，UnmanagedMemoryStream 不支持;
                    if (sourceType != typeof(MemoryStream))
                    {
                        throw new ArgumentException($"不支持的数据类型【{sourceType}】", nameof(value));
                    }
                }

                return converter.ConvertFrom(value);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return null;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}
